import type { PageType } from '../page_handler/type'
import { SearchDropdownType } from '../../module/page_enhancer/appearance/style_enhancement/platforms'
import {
  AppStyleCollections,
  BodyAttrs,
  ELEMENT_HIDE_TYPE,
  HOSTNAME,
} from '../../types/constants'
import { PageHandler } from '../page_handler'
import { BaseModule } from './base_module'

export interface HideConfig {
  selector?: string
  styleHandler?: () => void
}

export type PageHideConfig = Record<string, HideConfig>
export type PlatformHideConfig = Partial<Record<string, PageHideConfig>>

export abstract class BaseHideModule extends BaseModule {
  abstract styleId: string
  protected abstract getPlatformConfig(): PlatformHideConfig
  protected readonly pageType: PageType = PageHandler.getCurrentPageType()

  /**
   * 创建平台配置
   */
  createPlatformConfig<T extends Record<string, any>>(
    selectors: T,
    pageTypes: (keyof T)[],
    dropdownType: SearchDropdownType,
  ): Record<keyof T, { selector: string }> {
    const result: any = {}

    pageTypes.forEach((pageType) => {
      result[pageType] = {
        selector: selectors[pageType]!.searchBox.dropdown[dropdownType],
      }
    })

    return result
  }

  /**
   * 应用隐藏/显示逻辑
   */
  protected applyHide(show: boolean = false, type: SearchDropdownType): void {
    const platformConfig = this.getPlatformConfig()[HOSTNAME]

    if (!platformConfig)
      return

    const pageConfig = platformConfig[this.pageType]

    if (!pageConfig)
      return

    const { selector = '', styleHandler } = pageConfig

    if (show) {
      this.showElement(selector)
      this.unregisterStyle(this.styleId)
    }
    else {
      this.hideElement(selector)
      styleHandler ? styleHandler() : this.registerDefaultStyle(selector)
    }

    if (type === SearchDropdownType.History) {
      !show
        ? $(document.body).attr(AppStyleCollections.Search.attr.HIDE_HISTORY, 'true')
        : $(document.body).removeAttr(AppStyleCollections.Search.attr.HIDE_HISTORY)
    }
    else if (type === SearchDropdownType.Suggestions) {
      !show
        ? $(document.body).attr(AppStyleCollections.Search.attr.HIDE_SUGGESTIONS, 'true')
        : $(document.body).removeAttr(AppStyleCollections.Search.attr.HIDE_SUGGESTIONS)
    }
    else if (type === SearchDropdownType.HotRank) {
      !show
        ? $(document.body).attr(AppStyleCollections.Search.attr.HIDE_HOT_LISTS, 'true')
        : $(document.body).removeAttr(AppStyleCollections.Search.attr.HIDE_HOT_LISTS)
    }
  }

  /**
   * 隐藏元素
   */
  protected hideElement(selector: string): void {
    $(selector).attr(BodyAttrs.HIDE_TYPE, ELEMENT_HIDE_TYPE.ENGINE)
  }

  /**
   * 显示元素
   */
  protected showElement(selector: string): void {
    $(selector).removeAttr(BodyAttrs.HIDE_TYPE)
  }

  /**
   * 注册页面样式
   */
  protected registerDefaultStyle(selector: string): void {
    const style: string = `
${selector} {
  display: none !important;
}
    `
    this.registerStyle(this.styleId, style)
  }
}
